package com.lwj.liwanjia.view.activity.indent;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.lwj.liwanjia.R;
import com.lwj.liwanjia.adapter.IndentAdapter;
import com.lwj.liwanjia.base.BaseActivity;
import com.lwj.liwanjia.bean.AlipayBean;
import com.lwj.liwanjia.bean.CancleIndentBean;
import com.lwj.liwanjia.bean.DeleteUnpaidBean;
import com.lwj.liwanjia.bean.IndentDetailBean;
import com.lwj.liwanjia.bean.PwdBean;
import com.lwj.liwanjia.bean.QuerenBean;
import com.lwj.liwanjia.bean.WxBean;
import com.lwj.liwanjia.bean.YikaTongPayBean;
import com.lwj.liwanjia.impl.AlipayView;
import com.lwj.liwanjia.impl.CancleIndentView;
import com.lwj.liwanjia.impl.DeleteUnpaidView;
import com.lwj.liwanjia.impl.IndentDetailView;
import com.lwj.liwanjia.impl.IsSetPwdView;
import com.lwj.liwanjia.impl.QuerenView;
import com.lwj.liwanjia.impl.WxView;
import com.lwj.liwanjia.impl.YikatongPayView;
import com.lwj.liwanjia.presenter.CancleIndentPresenter;
import com.lwj.liwanjia.presenter.DeleteUnpaidPresenter;
import com.lwj.liwanjia.presenter.IndentAlipayPresenter;
import com.lwj.liwanjia.presenter.IndentDetailPresenter;
import com.lwj.liwanjia.presenter.IndentWxPayPresenter;
import com.lwj.liwanjia.presenter.IsSetPwdPresenter;
import com.lwj.liwanjia.presenter.QuerenIndentPresenter;
import com.lwj.liwanjia.presenter.YktPayPresenter;
import com.lwj.liwanjia.utils.CancleDialog;
import com.lwj.liwanjia.utils.PayDialog;
import com.lwj.liwanjia.utils.PopUtils;
import com.lwj.liwanjia.utils.PwdDialog;
import com.lwj.liwanjia.utils.RxBus;
import com.lwj.liwanjia.utils.SpfUtils;
import com.lwj.liwanjia.utils.TimeCountDown1;
import com.lwj.liwanjia.utils.ZfFangshiDialog;
import com.lwj.liwanjia.utils.ZfPwdDialog;
import com.lwj.liwanjia.view.activity.work.shang_jia.ding_dan.WuLiuActivity;
import com.superrecycleview.superlibrary.recycleview.SuperRecyclerView;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import constants.Constants;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class UnpaidActivity extends BaseActivity implements IndentDetailView, AlipayView, YikatongPayView, DeleteUnpaidView, CancleIndentView, QuerenView, WxView, IsSetPwdView {

    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.tv_minute)
    TextView tvMinute;//分钟
    @BindView(R.id.tv_second)
    TextView tvSecond;//秒
    @BindView(R.id.rlv_pay)
    SuperRecyclerView rlvPay;
    @BindView(R.id.status_bar)
    RelativeLayout statusBar;
    @BindView(R.id.iv_left)
    ImageView ivLeft;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.head_layout)
    RelativeLayout headLayout;
    @BindView(R.id.tv_quxiao_indent)
    TextView tvQuxiaoIndent;
    @BindView(R.id.ll_topay)
    LinearLayout llTopay;
    @BindView(R.id.tv_call)
    TextView tvCall;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;

    private IndentAdapter adapter;
    private List<IndentDetailBean.DataBean> list = new ArrayList<>();
    private PayStateViewHolder stateHolder;//订单状态
    private AddressViewHolder addressHolder;//收货地址
    private InforViewHolder infoHolder;//订单信息
    private ZfFangshiDialog zfFangshiDialog;//支付方式
    private PayDialog payDialog;
    private int checkPosition;//支付方式
    private String tradeId;
    private IndentDetailPresenter presenter;
    private String token;
    private long now;
    private TimeCountDown1 countDown1;
    private double totalpay;
    private IndentAlipayPresenter alipayPresenter;//支付宝支付
    private YktPayPresenter yktPayPresenter;//一卡通支付
    private IsSetPwdPresenter isSetPwdPresenter;//判断是否设置了支付密码
    private IndentWxPayPresenter indentWxPayPresenter;//微信支付
    private DeleteUnpaidPresenter deleteUnpaidPresenter;//删除待付款订单
    private CancleIndentPresenter canclePresenter;//待发货取消订单
    private QuerenIndentPresenter querenIndentPresenter;//确认收货
    private Map<String, Object> map = new HashMap<>();
    private String status;
    private CancleDialog dialog;//待付款,待发货，删除订单
    private IWXAPI api;
    private Subscription subscribe;
    private PwdDialog pwdDialog;//输入支付密码
    private String logistics;//物流单号

    @Override
    protected void initView() {
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        tradeId = getIntent().getStringExtra("tradeId");
        tvLeft.setVisibility(View.VISIBLE);
        tvTitle.setText("订单详情");
        ivRight.setVisibility(View.VISIBLE);
        ivRight.setImageResource(R.mipmap.fenlei);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        rlvPay.setLayoutManager(manager);
        rlvPay.setRefreshEnabled(false);
        rlvPay.setLoadMoreEnabled(false);
        adapter = new IndentAdapter(this, list);
        addView();
        rlvPay.setAdapter(adapter);
        presenter = new IndentDetailPresenter(this);
        alipayPresenter = new IndentAlipayPresenter(this);
        yktPayPresenter = new YktPayPresenter(this);
        deleteUnpaidPresenter = new DeleteUnpaidPresenter(this);
        canclePresenter = new CancleIndentPresenter(this);
        querenIndentPresenter = new QuerenIndentPresenter(this);
        indentWxPayPresenter = new IndentWxPayPresenter(this);
        isSetPwdPresenter = new IsSetPwdPresenter(this);
        token = SpfUtils.getSpfUtils(this).getToken();
        now = Calendar.getInstance().getTimeInMillis();
        subscribe = RxBus.getInstance().toObserverable(String.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                if (s.equals("支付完成")) {
                    finish();
                }
            }
        });
    }

    private void addView() {
        //订单状态
        View payStateView = LayoutInflater.from(this).inflate(R.layout.unpaid_head_layout, null);
        stateHolder = new PayStateViewHolder(payStateView);
        adapter.addHeaderView(payStateView);
        //收货地址
        View addressView = LayoutInflater.from(this).inflate(R.layout.unpaid_head_layout1, null);
        addressHolder = new AddressViewHolder(addressView);
        adapter.addHeaderView(addressView);
        //订单信息
        View footerView = LayoutInflater.from(this).inflate(R.layout.unpaid_footer_layout, null);
        infoHolder = new InforViewHolder(footerView);
        adapter.addFooterView(footerView);
    }

    @Override
    protected void initData() {
        if (tradeId != null) {
            presenter.getIndentDetailData(token, tradeId);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_unpaid;
    }


    @OnClick({R.id.tv_left, R.id.iv_right, R.id.tv_quxiao_indent, R.id.ll_topay, R.id.tv_call})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_left://返回
                finish();
                break;
            case R.id.iv_right://菜单
                PopUtils.getInstance().showPopupWindow(this, ivRight);
                break;
            case R.id.tv_quxiao_indent://取消订单，删除订单
                if (status.equals("待付款") || status.equals("订单取消")) {
                    dialog = new CancleDialog(this, status);
                    dialog.show();
                    dialog.getSure().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            deleteUnpaidPresenter.deleteUnpaidIndent(token, tradeId);
                            dialog.dismiss();
                        }
                    });
                } else if (status.equals("待发货")) {
                    dialog = new CancleDialog(this, status);
                    dialog.show();
                    dialog.getSure().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            canclePresenter.CancleIndent(token, tradeId);
                            dialog.dismiss();
                        }
                    });
                } else {
                    if (!TextUtils.isEmpty(logistics) && !logistics.equals("0")) {
                        Intent intent = new Intent(this, WuLiuActivity.class);
                        intent.putExtra("dingDanHao", tradeId);
                        startActivity(intent);
                    } else {
                        Toast.makeText(this, "超市商品无物流信息", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case R.id.ll_topay://付款
                map.put("token", token);
                map.put("tradeId", tradeId);
                payDialog = new PayDialog(this, totalpay);
                payDialog.show();
                //确认付款
                payDialog.getPay().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //选中了哪一种支付
                        checkPosition = payDialog.getCheckPosition();
                        if (checkPosition == 0) {//一卡通支付
                            isSetPwdPresenter.isSetPwd(token);
                        } else if (checkPosition == 1) {//支付宝支付
                            alipayPresenter.getIndentAlipayInfo(map);
                        } else if (checkPosition == 2) {//微信支付
                            indentWxPayPresenter.getIndentWxPayInfo(map);
                        }
                        payDialog.dismiss();
                    }
                });
                break;
            case R.id.tv_call:
                if (tvCall.getText().toString().equals("在线沟通")) {
                    Toast.makeText(this, "暂未开通", Toast.LENGTH_SHORT).show();
//                    Intent intent = new Intent(this, KefuActivity.class);
//                    startActivity(intent);
                } else if (tvCall.getText().toString().equals("确认收货")) {
                    querenIndentPresenter.querenIndent(token, tradeId);
                }
                break;
        }
    }

    @Override
    public void showError(Exception e) {
        Toast.makeText(this, "数据加载失败", Toast.LENGTH_SHORT).show();
    }

    /**
     * 判断是否设置过一卡通支付密码
     *
     * @param pwdBean
     */
    @Override
    public void isSetPwd(PwdBean pwdBean) {
        if (pwdBean.getState() == 0) {
            Toast.makeText(this, "访问失败", Toast.LENGTH_SHORT).show();
        } else if (pwdBean.getState() == 1) {
            if (pwdBean.isData()) {//设置过支付密码
                pwdDialog = new PwdDialog(this);
                pwdDialog.show();
                pwdDialog.setOnFinishInput(new PwdDialog.OnPasswordInputFinish() {
                    @Override
                    public void inputFinish() {
                        map.put("payPassword", pwdDialog.getStrPassword());
                        yktPayPresenter.getYktpayInfo(map);
                    }
                });
            } else {
                ZfPwdDialog zfPwdDialog = new ZfPwdDialog(this);
                zfPwdDialog.show();
            }
        }
    }


    /**
     * 确认收货
     *
     * @param querenBean
     */
    @Override
    public void querenIndent(QuerenBean querenBean) {
        if (querenBean.getState() == 1) {
            if (querenBean.getData().getStatus().equals("订单完成")) {
                Toast.makeText(this, "确认收货成功", Toast.LENGTH_SHORT).show();
                finish();
            } else {
                Toast.makeText(this, "确认收货失败", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "访问失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 退款申请
     *
     * @param cancleIndentBean
     */
    @Override
    public void cancleIndent(CancleIndentBean cancleIndentBean) {
        if (cancleIndentBean.getState() == 0) {
            Toast.makeText(this, "申请失败", Toast.LENGTH_SHORT).show();
        } else if (cancleIndentBean.getState() == 1) {
            if (cancleIndentBean.getData().getStatus().equals("退款申请")) {
                Toast.makeText(this, "退款申请成功", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    /**
     * 删除待付款订单
     *
     * @param deleteUnpaidBean
     */
    @Override
    public void deleteUnpaidIndent(DeleteUnpaidBean deleteUnpaidBean) {
        if (deleteUnpaidBean.getState() == 0) {
            Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show();
        } else if (deleteUnpaidBean.getState() == 1) {
            if (deleteUnpaidBean.getData().getStatus().equals("删除成功")) {
                Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    /**
     * 微信支付
     *
     * @param wxBean
     */
    @Override
    public void getWxPayInfo(WxBean wxBean) {
        if (wxBean.getState() == 0) {
            Toast.makeText(this, "接口有误", Toast.LENGTH_SHORT).show();
        } else if (wxBean.getState() == 1) {
            WxBean.DataBean data = wxBean.getData();
            PayReq req = new PayReq();
            req.appId = data.getMsg().getAppid();
            req.partnerId = data.getMsg().getPartnerid();
            req.prepayId = data.getMsg().getPrepayid();
            req.nonceStr = data.getMsg().getNoncestr();
            req.timeStamp = String.valueOf(data.getMsg().getTimestamp());
            req.packageValue = data.getMsg().getPackageX();
            req.sign = data.getMsg().getSign();
            api.sendReq(req);
        }
    }

    /**
     * 一卡通支付
     *
     * @param yikaTongPayBean
     */
    @Override
    public void getYktpayInfor(YikaTongPayBean yikaTongPayBean) {
        if (yikaTongPayBean.getState() == 0) {
            Toast.makeText(this, "支付失败", Toast.LENGTH_SHORT).show();
        } else if (yikaTongPayBean.getState() == 1) {
            if (yikaTongPayBean.getData().isSuccess()) {
                Toast.makeText(UnpaidActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                finish();
                pwdDialog.dismiss();
            } else {
                Toast.makeText(this, "支付失败", Toast.LENGTH_SHORT).show();
                finish();
            }
        } else if (yikaTongPayBean.getState() == 3) {//密码有误
            TextView[] tvList = pwdDialog.getTvList();
            for (TextView tv : tvList) {
                tv.setText("");
            }
            pwdDialog.getTvError().setVisibility(View.VISIBLE);
        } else if (yikaTongPayBean.getState() == 11) {
            Toast.makeText(this, "余额不足", Toast.LENGTH_SHORT).show();
            pwdDialog.dismiss();
        }
    }

    /**
     * 支付宝支付
     *
     * @param alipayBean
     */
    @Override
    public void getAlipayInfo(AlipayBean alipayBean) {
        if (alipayBean.getState() == 0) {
            Toast.makeText(this, "接口有误", Toast.LENGTH_SHORT).show();
        } else {
            final String orderInfo = alipayBean.getData().getAliAppPay();
            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    PayTask alipay = new PayTask(UnpaidActivity.this);
                    Map<String, String> result = alipay.payV2(orderInfo, true);
                    String resultStatus = result.get("resultStatus");
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = resultStatus;
                    mHandler.sendMessage(msg);
                }
            };
            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                String resultStatus = (String) msg.obj;
                if (resultStatus.equals("9000")) {
                    Toast.makeText(UnpaidActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    finish();
                } else if (resultStatus.equals("4000")) {
                    Toast.makeText(UnpaidActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(UnpaidActivity.this, "支付取消", Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    /**
     * 获取订单详情
     *
     * @param indentDetailBean
     */
    @Override
    public void getIndentDetailData(IndentDetailBean indentDetailBean) {
        if (indentDetailBean.getState() == 0) {
            Toast.makeText(this, "接口有误", Toast.LENGTH_SHORT).show();
        } else {
            IndentDetailBean.DataBean data = indentDetailBean.getData();
            totalpay = data.getTotalpay();
            setPayStateInfo(data);
            setAddress(data);
            list.clear();
            list.add(data);
            adapter.notifyDataSetChanged();
            setIndentInfo(data);
            if (countDown1 != null) {
                countDown1.cancel();
            }
            long endTime = data.getEndPayTime();
            countDown1 = new TimeCountDown1(endTime - now, 1000, tvMinute, tvSecond);
            countDown1.start();
        }
    }


    /**
     * 订单状态
     *
     * @param data
     */
    private void setPayStateInfo(IndentDetailBean.DataBean data) {
        status = data.getStatus();
        stateHolder.tvPayState.setText(status);
        if (status.equals("订单取消")) {
            stateHolder.tvPayState.setText("已取消");
            stateHolder.ivPayState.setImageResource(R.mipmap.cancel);
            stateHolder.tvPrice.setText("订单已取消");
            tvQuxiaoIndent.setText("删除订单");
            llTopay.setVisibility(View.GONE);
            tvCall.setVisibility(View.VISIBLE);
            tvCall.setText("在线沟通");
        } else if (status.equals("待付款")) {
            stateHolder.ivPayState.setImageResource(R.mipmap.daifukuang);
            stateHolder.tvPrice.setText("还需支付￥" + data.getTotalpay());
            tvQuxiaoIndent.setText("删除订单");
        } else if (status.equals("待发货")) {
            stateHolder.ivPayState.setImageResource(R.mipmap.daifahuo);
            stateHolder.tvPrice.setText("等待商家发货...");
            llTopay.setVisibility(View.GONE);
            tvCall.setVisibility(View.VISIBLE);
            tvCall.setText("在线沟通");
        } else if (status.equals("待收货")) {
            stateHolder.tvPayState.setText("待收货");
            stateHolder.ivPayState.setImageResource(R.mipmap.yifahuo);
            stateHolder.tvPrice.setText("商品正在运输中...");
            llTopay.setVisibility(View.GONE);
            tvCall.setVisibility(View.VISIBLE);
            tvCall.setText("确认收货");
            tvQuxiaoIndent.setText("查看物流");

        } else if (status.equals("已完成")) {
            stateHolder.tvPayState.setText("已完成");
            stateHolder.ivPayState.setImageResource(R.mipmap.yiwancheng);
            stateHolder.tvPrice.setText("交易已完成...");
            llTopay.setVisibility(View.GONE);
            tvCall.setVisibility(View.VISIBLE);
            tvCall.setText("在线沟通");
            tvQuxiaoIndent.setText("查看物流");
        } else {
            stateHolder.tvPayState.setText(status);
            stateHolder.ivPayState.setImageResource(R.mipmap.weitongyi);
            stateHolder.tvPrice.setText("退货、退款申请未同意...");
            llTopay.setVisibility(View.GONE);
            tvCall.setVisibility(View.VISIBLE);
            tvCall.setText("在线沟通");
            tvQuxiaoIndent.setText("查看物流");
        }
    }

    /**
     * 设置地址
     *
     * @param data
     */
    private void setAddress(IndentDetailBean.DataBean data) {
        addressHolder.tvName.setText(data.getConsignee().getConsigneeName());
        addressHolder.tvAddress.setText(data.getConsignee().getConsigneeAddress());
        addressHolder.tvPhone.setText(data.getConsignee().getConsigneePhone());
    }

    /**
     * 订单信息
     *
     * @param data
     */
    private void setIndentInfo(IndentDetailBean.DataBean data) {
        infoHolder.tvBianhao.setText(data.getTradeId());
        logistics = data.getLogistics();
        long orderTime = data.getOrderTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String s = format.format(orderTime);
        infoHolder.tvTime.setText(s);
        infoHolder.tvPayFangshi.setText(data.getPayWay());
        if (data.getLiwanjiaInvoice() != null && !TextUtils.isEmpty(data.getLiwanjiaInvoice())) {
            infoHolder.tvFapiao.setText(data.getLiwanjiaInvoice());
        }
        if (!TextUtils.isEmpty(data.getPayInfo()) && data.getPayInfo() != null) {
            infoHolder.tvLiuyan.setText(data.getPayInfo());
        }
    }

    /**
     * 订单状态
     */
    static class PayStateViewHolder {
        @BindView(R.id.iv_pay_state)
        ImageView ivPayState;
        @BindView(R.id.tv_pay_state)
        TextView tvPayState;
        @BindView(R.id.tv_price)
        TextView tvPrice;

        PayStateViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    /**
     * 收货地址
     */
    static class AddressViewHolder {
        @BindView(R.id.tv_name)
        TextView tvName;
        @BindView(R.id.tv_phone)
        TextView tvPhone;
        @BindView(R.id.tv_address)
        TextView tvAddress;

        AddressViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    /**
     * 订单信息
     */
    static class InforViewHolder {
        @BindView(R.id.tv_bianhao)
        TextView tvBianhao;
        @BindView(R.id.tv_time)
        TextView tvTime;
        @BindView(R.id.tv_pay_fangshi)
        TextView tvPayFangshi;
        @BindView(R.id.tv_fapiao)
        TextView tvFapiao;
        @BindView(R.id.tv_liuyan)
        TextView tvLiuyan;
        @BindView(R.id.ll_liuyan)
        LinearLayout llLiuyan;

        InforViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    @Override
    protected void onDestroy() {
        if (presenter != null) {
            presenter = null;
        }
        if (alipayPresenter != null) {
            alipayPresenter = null;
        }
        if (yktPayPresenter != null) {
            yktPayPresenter = null;
        }
        if (indentWxPayPresenter != null) {
            indentWxPayPresenter = null;
        }
        if (deleteUnpaidPresenter != null) {
            deleteUnpaidPresenter = null;
        }
        if (canclePresenter != null) {
            canclePresenter = null;
        }
        if (querenIndentPresenter != null) {
            querenIndentPresenter = null;
        }
        if (isSetPwdPresenter != null) {
            isSetPwdPresenter = null;
        }
        if (!subscribe.isUnsubscribed()) {
            subscribe.unsubscribe();
        }
        super.onDestroy();

    }
}
